package com.hsgene.user.service.impl;

import com.google.common.base.Strings;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.web.session.SessionConstants;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.common.util.web.session.UserInfoExtra;
import com.hsgene.common.util.web.session.UserSession;
import com.hsgene.user.exception.UserErrorCode;
import com.hsgene.user.service.LoginCheckService;
import com.hsgene.user.session.UserSessionComponent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * @author wangbing
 * @version 1.0, 2018/10/16
 */
@Service
public class LoginCheckServiceImpl implements LoginCheckService {

    @Resource
    private RedisTemplate<String, UserSession> redisTemplate;

    @Resource
    private UserSessionComponent userSessionComponent;

    @Override
    public ApiResult<UserInfo> checkLoginStatus(String sessionId, String accessToken) {

        if (!Strings.isNullOrEmpty(sessionId) && !Strings.isNullOrEmpty(accessToken)) {
            UserSession session = redisTemplate.opsForValue().get(UserSessionComponent.getRedisSessionKey(sessionId));
            if (session != null) {
                UserInfo userInfo = session.getUserInfo();
                if ("0".equals(userInfo.getUserType())) {
                    UserInfoExtra extra = userInfo.getExtra();
                    if (extra.getFirstLogin()) {
                        return ApiResult.fail(UserErrorCode.FIRST_LOGIN_VERIFY);
                    }
                }
                if (accessToken.equals(session.getAccessToken())) {
                    if (!session.isAccessTokenExpired()) {
                        // fix[BUG-17741]，刷新用户的access_token过期时间
                        if (UserSession.ACCESS_TOKEN_EXPIRE_TIME > 0) {
                            LocalDateTime expireTime = LocalDateTime.now().plus(UserSession.ACCESS_TOKEN_EXPIRE_TIME, ChronoUnit.MINUTES);
                            session.setExpireTime(expireTime);
                            // 将会话信息存入Redis
                            userSessionComponent.saveSession(session);
                        }
                        return ApiResult.succ(session.getUserInfo());
                    } else {
                        return ApiResult.fail(UserErrorCode.USER_TOKEN_EXPIRED);
                    }
                } else if (accessToken.equals(session.getOldAccessToken())) {
                    return ApiResult.fail(UserErrorCode.USER_TOKEN_REFRESHED);
                } else {
                    return ApiResult.fail(UserErrorCode.USER_TOKEN_LOGGED_OTHER);
                }
            }
        }

        return ApiResult.fail(UserErrorCode.USER_NOT_LOGIN);
    }
}
